import type { ColumnsType } from 'antd/es/table'
import React, { useEffect, useState, Key } from 'react'
import {
  Button,
  Form,
  Input,
  Card,
  Space,
  Table,
  Tag,
  Tooltip,
  message,
  Modal,
  Checkbox,
  Divider
} from 'antd'
import { SearchOutlined, EditOutlined, DeleteOutlined, UserOutlined } from '@ant-design/icons'
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
// 引入列表请求函数

import { reqUserList, reqAddOrUpdateUser, reqToAssign, reqDoAssign, reqDeleteUser } from '@/api/user/index'


export default function User() {
  // 当前页
  const [current, setCurrent] = useState(1)
  // 一页几条
  const [pageSize, setPageSize] = useState(3)
  // 列表数据
  const [userList, setUserList] = useState([])
  // 数据总条数
  const [total, setTotal] = useState(0)
  // 搜索
  const [search, setSearch] = useState({
    username: ''
  })
  // 添加用户的数据
  const [userData, setUserData] = useState({
    id: '',
    username: '',
    nickName: '',
    password: ''
  })
  // loading
  const [loading, setLoading] = useState(false);
  // 设置用户角色
  // 存储全部角色名字列表
  const [allRolesList,setAllRolesList] = useState<any>([])
  // 存储选中的角色id的数组
  const [assignRoles,setAssignRoles] = useState<any>([])

  const CheckboxGroup = Checkbox.Group;
  const [checkedList, setCheckedList] = useState(assignRoles);
  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(false);

  // 挂载
  useEffect(() => {
    getUserList(current, pageSize, search)
  }, [])
  // 获取用户的数据回调
  async function getUserList(current: number, pageSize: number, search: object) {
    setLoading(true)
    let result = await reqUserList(current, pageSize, search)
    // console.log(result);
    setUserList(result.items)
    setTotal(result.total)
    setLoading(false)
  }
  //弹框的默认值 设置模态框是否显示
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalOpen1, setIsModalOpen1] = useState(false);
  // // 选中的数据id存储的状态 react提供的类型Key，表示不重复的值
  const [selectKeys, setSelectKeys] = useState<Key[]>([])
  // 定义一个设置模态框中那个数据显示的变量
  const [flag, setFlag] = useState(true)
  // 创建form实例 
  const [form] = Form.useForm()
  const [form1] = Form.useForm()
  const [form2] = Form.useForm()
  // 查询用户的回调
  function searchUser() {
    let searchUser = form1.getFieldsValue()
    search.username = searchUser.username
    // 根据username 获取查询的结果
    getUserList(current, pageSize, search)
    console.log("设置值", search, "获取的表单", searchUser)
  }
  // 清空搜索框的表单的数据
  function clearData() {
    // 先清空表单的数据
    form1.resetFields()
    // 清空搜索携带的username
    search.username = ''
    // console.log(current, pageSize, search)
    // 在重新获取数据
    getUserList(current, pageSize, search)
  }
  // 添加用户的回调
  async function addUser() {
    // 决定显示的是那个模态框  添加的
    setFlag(false)
    // 请用每条数据携带的id  
    userData.id = ''
    // 清空表单的数据
    form.resetFields()
    // 设置打开模态框
    setIsModalOpen(true)

  }
  // 点击模态框确定的按钮
  async function handleOk() {
    // 获取模态框表单的数据
    let data = form.getFieldsValue()
    console.log("获取表单的数据", data)
    userData.username = data.username
    userData.nickName = data.nickName
    // 设置用户需要的参数
    console.log("设置的表单要渲染的数据", userData)
    // 发送添加修改的请求
    let result = await reqAddOrUpdateUser(userData)
    // console.log(result)
    setIsModalOpen(false)
    // 添加修改成功之后,重新获取数据
    getUserList(current, pageSize, search)
  }
  // 点击取消按钮的回调
  function handleCancel() {
    setIsModalOpen(false)
  }



  // 分配角色
  const onChange = (list: CheckboxValueType[]) => {
    setCheckedList(list as any);
    setIndeterminate(!!list.length && list.length < allRolesList.length);
    setCheckAll(list.length === allRolesList.length);
    setAssignRoles(list)
  };

  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    let list = allRolesList.map((item:any)=>item.value)
    setAssignRoles(list)
    setCheckedList(e.target.checked ? list : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };

  // 点击模态框确定的按钮
  async function handleOk1() {
    console.log(checkedList,'1111');
    // console.log(userData.id);
    let userId = userData.id
    let ids = assignRoles.join(',')
   await reqDoAssign(userId,ids)
    message.success('设置角色成功')
    setIsModalOpen1(false)
    getUserList(current, pageSize, search)
  }
  // 点击取消按钮的回调
  function handleCancel1() {
    setIsModalOpen1(false)
  }
  // 表格要的数据
  const columns: ColumnsType<any> = [
    {
      title: '序号',
      dataIndex: 'name',
      key: 'name',
      render: (text, records, index) => {
        return index + 1
      },
      align: 'center',
      width: 120,
    },
    {
      title: '用户名',
      align: 'center',
      dataIndex: 'username',
    },
    {
      title: '用户昵称',
      align: 'center',
      dataIndex: 'nickName',
    },
    {
      title: '角色列表',
      align: 'center',
      dataIndex: 'roleName',
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'gmtCreate',
    },
    {
      title: '更新时间',
      align: 'center',
      dataIndex: 'gmtModified',
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space>
            <Tooltip title="角色分配">
              <Button icon={<UserOutlined />} type="primary" onClick={async () => {
                // 设置打开模态框
                setIsModalOpen1(true)
                console.log(data);
                setUserData(data)
                form2.setFieldsValue({ username: data.username })
                let result = await reqToAssign(data.id)
                console.log(result);
                // 存储全部角色名字和id列表
                setAllRolesList(result.allRolesList.map((item:any)=>{
                  return {
                    label:item.roleName,
                    value:item.id
                  }
                }))
                //存储选中的角色id的数组
                setAssignRoles(result.assignRoles.map((item:any)=>item.id))
                setCheckedList(result.assignRoles.map((item:any)=>item.id))
                // 存储全部角色列表
                // setAllRoles((result.allRolesList))
                // setAssignRolesId(result.assignRoles.map((item:any)=>item.id))
              }}></Button>
            </Tooltip>
            <Tooltip title="修改">
              <Button icon={<EditOutlined />} type="primary" onClick={() => {
                // console.log(data)
                setFlag(false)
                // 设置打开模态框
                setIsModalOpen(true)
                // 设置模态显示里面的数据
                let result = form.setFieldsValue(data)
                userData.id = data.id

                let result1 = form.getFieldsValue()
                console.log("点击模态框之后获取的表单数据", result1)
              }}></Button>
            </Tooltip>
            <Tooltip title="删除">
              <Button icon={<DeleteOutlined />} type="primary" danger onClick={async () => {
                await reqDeleteUser(data.id)
                getUserList(current, pageSize, search)
              }}></Button>
            </Tooltip>
          </Space>
        )
      },
      fixed: 'right',
      width: 300,
      align: 'center',
    },
  ]

  return (
    <Card style={{ margin: 20 }}>
      <Form
        style={{ marginBottom: 20 }}
        layout="inline" //水平排列
        form={form1}
      >
        <Form.Item name='username'>
          <Input placeholder="用户名" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />} onClick={searchUser} >
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={clearData} >清空</Button>
        </Form.Item>
      </Form>
      <Button type="primary" style={{ marginRight: 10 }} onClick={addUser} >
        添加
      </Button>
      {/* 有长度就是选中 false解除禁用*/}
      <Button type="primary" danger>
        批量删除
      </Button>
      {/* 表格 */}
      <Table
        columns={columns}
        style={{ marginTop: 20 }}
        bordered
        scroll={{ x: 1500 }}
        rowKey="id"
        dataSource={userList}
        // 展示表格中的复选框
        rowSelection={{
          // 点击了，onChange就会触发，会拿到最新的id
          onChange(selectedRowKeys) {
            // selectedRowKeys是选中数据的id数组，存起来
            setSelectKeys(selectedRowKeys)
          },
        }}
        // 分页器
        pagination={{
          current,//current值是几对应页码高亮
          total,
          pageSize,
          showSizeChanger: true,
          pageSizeOptions: [2, 5, 10],
          showQuickJumper: true,
          showTotal: function (total) {
            return `总共:${total}条`
          },
          onChange: function (page: number, pageSize: number) {
            setPageSize(pageSize)
            setCurrent(page)
            getUserList(current, pageSize, search)
          }
        }}
        loading={loading}
      />
      {/* 添加|修改弹框 */}
      <Modal title={userData.id ? '修改品牌' : '添加品牌'} visible={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        {/* 添加修改 */}
        {!flag ? <Form
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          autoComplete="off"
          form={form}
        >
          {/* 用户名 */}
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '用户名!' }]}
          >
            <Input placeholder='品牌名称' />
          </Form.Item>
          {/* 用户昵称 */}
          <Form.Item
            label="用户昵称"
            name="nickName"
            rules={[{ required: true, message: '请输入用户昵称!' }]}
          >
            <Input placeholder='品牌名称' />
          </Form.Item>
          {userData.id ? '' : <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input placeholder='密码框' />
          </Form.Item>}

        </Form> : ''}
      </Modal>
      {/* 分配角色 */}
      <Modal title="分配角色" visible={isModalOpen1} onOk={handleOk1} onCancel={handleCancel1}>
        <Form
          style={{ marginBottom: 20 }}
          form={form2}
        >
          <Form.Item name='username' label="用户名">
            <Input />
          </Form.Item>
          <Form.Item label="角色列表">
            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
              全选
            </Checkbox>
            <Divider />
            <CheckboxGroup options={allRolesList} value={checkedList} onChange={onChange} />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  )
}
